<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { generateChatId } from '../utils'

const props = defineProps({
  title: {
    type: String,
    required: true
  },
  chatFunction: {
    type: Function,
    required: true
  }
})

const chatId = ref(generateChatId())
const messages = ref([])
const inputMessage = ref('')
const eventSource = ref(null)
const isLoading = ref(false)

// 发送消息
const sendMessage = () => {
  if (!inputMessage.value.trim()) return
  
  // 添加用户消息
  messages.value.push({
    content: inputMessage.value,
    isUser: true,
    time: new Date().toLocaleTimeString()
  })
  
  // 设置加载状态
  isLoading.value = true
  
  // 调用聊天函数
  eventSource.value = props.chatFunction(inputMessage.value, chatId.value)
  
  // 监听SSE事件
  eventSource.value.onmessage = (event) => {
    // 检查是否已有AI消息，如果有则追加内容，否则添加新消息
    const lastMessage = messages.value[messages.value.length - 1]
    
    if (!lastMessage.isUser) {
      // 追加新内容到现有消息
      lastMessage.content += event.data
    } else {
      // 创建新的AI消息
      messages.value.push({
        content: event.data,
        isUser: false,
        time: new Date().toLocaleTimeString()
      })
    }
    
    // 滚动到底部
    scrollToBottom()
  }
  
  eventSource.value.onerror = () => {
    closeEventSource()
    isLoading.value = false
  }
  
  eventSource.value.onopen = () => {
    // 清空输入框
    inputMessage.value = ''
  }
  
  // 添加结束事件监听
  eventSource.value.addEventListener('complete', () => {
    closeEventSource()
    isLoading.value = false
  })
}

// 关闭EventSource连接
const closeEventSource = () => {
  if (eventSource.value) {
    eventSource.value.close()
    eventSource.value = null
  }
}

// 滚动到底部
const scrollToBottom = () => {
  setTimeout(() => {
    const chatContainer = document.querySelector('.chat-messages')
    if (chatContainer) {
      chatContainer.scrollTop = chatContainer.scrollHeight
    }
  }, 50)
}

// 组件卸载时关闭连接
onUnmounted(() => {
  closeEventSource()
})

// 组件挂载时添加欢迎消息
onMounted(() => {
  messages.value.push({
    content: `欢迎来到${props.title}，开始聊天吧！`,
    isUser: false,
    time: new Date().toLocaleTimeString()
  })
  
  // 初始滚动到底部
  scrollToBottom()
})
</script>

<template>
  <div class="chat-container">
    <div class="chat-header">
      <h2>{{ title }}</h2>
      <div class="chat-id">会话ID: {{ chatId }}</div>
    </div>
    
    <div class="chat-messages">
      <div 
        v-for="(message, index) in messages" 
        :key="index" 
        :class="['message', message.isUser ? 'user-message' : 'ai-message']"
      >
        <div class="message-content">
          <div class="message-text">{{ message.content }}</div>
          <div class="message-time">{{ message.time }}</div>
        </div>
      </div>
      
      <div v-if="isLoading" class="loading-indicator">
        <div class="dot-flashing"></div>
      </div>
    </div>
    
    <div class="chat-input">
      <input 
        v-model="inputMessage" 
        @keyup.enter="sendMessage" 
        type="text" 
        placeholder="输入消息..." 
        :disabled="isLoading"
      />
      <button @click="sendMessage" :disabled="isLoading || !inputMessage.trim()">
        发送
      </button>
    </div>
  </div>
</template>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  max-width: 800px;
  margin: 0 auto;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  background-color: #fff;
}

.chat-header {
  padding: 15px;
  border-bottom: 1px solid #eee;
  background-color: #f8f9fa;
  border-radius: 8px 8px 0 0;
}

.chat-header h2 {
  margin: 0;
  font-size: 1.2rem;
  color: #333;
}

.chat-id {
  font-size: 0.8rem;
  color: #888;
  margin-top: 5px;
}

.chat-messages {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.message {
  display: flex;
  margin-bottom: 10px;
  max-width: 80%;
}

.user-message {
  align-self: flex-end;
}

.ai-message {
  align-self: flex-start;
}

.message-content {
  padding: 10px 15px;
  border-radius: 18px;
  position: relative;
}

.user-message .message-content {
  background-color: #007bff;
  color: white;
  border-bottom-right-radius: 4px;
}

.ai-message .message-content {
  background-color: #f1f1f1;
  color: #333;
  border-bottom-left-radius: 4px;
}

.message-time {
  font-size: 0.7rem;
  opacity: 0.7;
  margin-top: 5px;
  text-align: right;
}

.chat-input {
  display: flex;
  padding: 15px;
  border-top: 1px solid #eee;
}

.chat-input input {
  flex: 1;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 20px;
  outline: none;
  font-size: 1rem;
}

.chat-input button {
  margin-left: 10px;
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.2s;
}

.chat-input button:hover {
  background-color: #0069d9;
}

.chat-input button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.loading-indicator {
  display: flex;
  justify-content: center;
  margin: 10px 0;
}

.dot-flashing {
  position: relative;
  width: 10px;
  height: 10px;
  border-radius: 5px;
  background-color: #9880ff;
  color: #9880ff;
  animation: dot-flashing 1s infinite linear alternate;
  animation-delay: 0.5s;
}

.dot-flashing::before, .dot-flashing::after {
  content: '';
  display: inline-block;
  position: absolute;
  top: 0;
}

.dot-flashing::before {
  left: -15px;
  width: 10px;
  height: 10px;
  border-radius: 5px;
  background-color: #9880ff;
  color: #9880ff;
  animation: dot-flashing 1s infinite alternate;
  animation-delay: 0s;
}

.dot-flashing::after {
  left: 15px;
  width: 10px;
  height: 10px;
  border-radius: 5px;
  background-color: #9880ff;
  color: #9880ff;
  animation: dot-flashing 1s infinite alternate;
  animation-delay: 1s;
}

@keyframes dot-flashing {
  0% {
    background-color: #9880ff;
  }
  50%, 100% {
    background-color: rgba(152, 128, 255, 0.2);
  }
}
</style>